package weiy.top.modules.attr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import weiy.top.common.util.PageUtils;
import weiy.top.constant.ProductConstant;
import weiy.top.modules.attr.entity.PmsAttr;
import weiy.top.modules.attr.entity.PmsAttrAttrgroupRelation;
import weiy.top.modules.attr.entity.PmsAttrGroup;
import weiy.top.modules.attr.mapper.PmsAttrMapper;
import weiy.top.modules.attr.service.IPmsAttrAttrgroupRelationService;
import weiy.top.modules.attr.service.IPmsAttrGroupService;
import weiy.top.modules.attr.service.IPmsAttrService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import weiy.top.modules.attr.vo.AttrGroupRelationVo;
import weiy.top.modules.attr.vo.AttrRespVo;
import weiy.top.modules.attr.vo.AttrVo;
import weiy.top.modules.category.entity.PmsCategory;
import weiy.top.modules.category.service.IPmsCategoryService;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: pms_attr
 * @Author: weihancheng
 * @Date: 2021-11-24
 * @Version: V1.0
 */
@Service
public class PmsAttrServiceImpl extends ServiceImpl<PmsAttrMapper, PmsAttr> implements IPmsAttrService {

    @Autowired
    private IPmsAttrAttrgroupRelationService attrgroupRelationService;

    @Autowired
    private IPmsAttrGroupService attrGroupService;

    @Autowired
    private IPmsCategoryService categoryService;

    @Override
    public void saveMain(AttrVo attrVo) {
        PmsAttr attrEntity = new PmsAttr();
        BeanUtils.copyProperties(attrVo, attrEntity);
        save(attrEntity);

        // 保存关联关系
        if (attrVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()
                && StringUtils.isNotEmpty(attrVo.getAttrGroupId())) {
            PmsAttrAttrgroupRelation attrgroupRelation = new PmsAttrAttrgroupRelation();
            attrgroupRelation.setAttrId(attrEntity.getAttrId());
            attrgroupRelation.setAttrGroupId(attrVo.getAttrGroupId());

            attrgroupRelationService.save(attrgroupRelation);
        }
    }

    @Override
    public PageUtils queryBaseAttrPageList(HttpServletRequest req, QueryWrapper<PmsAttr> queryWrapper, Page<PmsAttr> page) {
        String type = req.getParameter("type");
        // 判断是销售属性还是基本属性，拿到对应的code
        int code = "base".equalsIgnoreCase(type) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode();
        queryWrapper.eq("attr_type", code);

        String catelogId = req.getParameter("catelog_id");
        if (!catelogId.equals("0")) {
            queryWrapper.eq("catelog_id", catelogId);
        }

        IPage<PmsAttr> pageList = page(page, queryWrapper);

        List<PmsAttr> records = pageList.getRecords();
        List<AttrRespVo> attrRespVoList = records.stream().map((entity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(entity, attrRespVo);

            //1、设置分类和分组的名字
            if ("base".equalsIgnoreCase(type)) {
                // 根据属性，查询对应的属性分组

                // 按照属性id 在 关联表 查出分组id
                LambdaQueryWrapper<PmsAttrAttrgroupRelation> relationQW = new LambdaQueryWrapper<>();
                relationQW.eq(PmsAttrAttrgroupRelation::getAttrId, entity.getAttrId());
                PmsAttrAttrgroupRelation relation = attrgroupRelationService.getOne(relationQW);

                if (relation != null && StringUtils.isNotEmpty(relation.getAttrGroupId())) {
                    // 根据分组id查询分组名字
                    PmsAttrGroup attrGroupEntity = attrGroupService.getById(relation.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            return attrRespVo;
        }).collect(Collectors.toList());

        PageUtils data = new PageUtils(page);
        data.setRecords(attrRespVoList);
        return data;
    }

    @Override
    public AttrRespVo getByIdMain(String id) {
        AttrRespVo attrRespVo = new AttrRespVo();
        PmsAttr attrEntity = this.getById(id);
        BeanUtils.copyProperties(attrEntity, attrRespVo);

        // 如果是基础属性，那么就设置基础属性信息
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 设置分组信息
            PmsAttrGroup group = getGroupByAttrId(attrEntity.getAttrId());
            if (group != null) {
                attrRespVo.setGroupName(group.getAttrGroupName());
            }
        }

        // 设置分类信息
        String catelogId = attrEntity.getCatelogId();
        String[] catelogPath = categoryService.getCatelogPathByCatelogId(catelogId);
        attrRespVo.setCatelogPath(catelogPath);

        PmsCategory categoryEntity = categoryService.getById(catelogId);
        if(categoryEntity!=null){
            // 分组名字
            attrRespVo.setCatelogName(categoryEntity.getName());
        }

        return attrRespVo;
    }

    @Override
    public void updateByIdMain(AttrVo attrVo) {
        PmsAttr attrEntity = new PmsAttr();
        BeanUtils.copyProperties(attrVo, attrEntity);

        // 更新属性表
        this.updateById(attrEntity);

        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //1、更新关联表
            PmsAttrAttrgroupRelation relationEntity = new PmsAttrAttrgroupRelation();
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            relationEntity.setAttrId(attrVo.getAttrId());

            LambdaQueryWrapper<PmsAttrAttrgroupRelation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(PmsAttrAttrgroupRelation::getAttrId, attrVo.getAttrId());
            int count = attrgroupRelationService.count(queryWrapper);

            if (count > 0) {
                attrgroupRelationService.update(relationEntity, queryWrapper);
            } else {
                attrgroupRelationService.save(relationEntity);
            }
        }
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        List<PmsAttrAttrgroupRelation> entities = Arrays.asList(vos).stream().map(item -> {
            PmsAttrAttrgroupRelation relationEntity = new PmsAttrAttrgroupRelation();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());

        attrgroupRelationService.deleteBatchRelation(entities);
    }

    private PmsAttrGroup getGroupByAttrId(String attrId) {
        LambdaQueryWrapper<PmsAttrAttrgroupRelation> relationQW = new LambdaQueryWrapper<>();
        relationQW.eq(PmsAttrAttrgroupRelation::getAttrId, attrId);
        PmsAttrAttrgroupRelation relation = attrgroupRelationService.getOne(relationQW);

        if (relation != null && StringUtils.isNotEmpty(relation.getAttrGroupId())) {
            // 根据分组id查询分组名字
            return attrGroupService.getById(relation.getAttrGroupId());
        }
        return null;
    }
}
